// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DifferentialDriveTrackingAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Navigation.Runtime.Motion
{
    using System;
    using System.Runtime.Serialization;
    using Microsoft.Robotics.Hardware.DAC;
    using Microsoft.Robotics.Hardware.Runtime.DAC;
    using Microsoft.Robotics.Navigation.Runtime.Motion;
    using Microsoft.Robotics.Runtime;

    /// <summary>
    /// Generates commands to a differential drive robot to track a desired velocity 
    /// </summary>
    [DataContract]
    public class DifferentialDriveTrackingAgent : Agent, ISubscriptionReceiver<MobileBaseVelocityReferenceMessage>
    {
        /// <summary>
        /// Name of the agent producing a mobile base velocity reference
        /// </summary>
        [DataMember(Name = "MobileBaseVelocityReferenceProducer")]
        private string mobileBaseVelocityReferenceProducer = default(string);

        /// <summary>
        /// Name of the heartbeat agent
        /// </summary>
        [DataMember(Name = "HeartbeatAgent")]
        private string heartbeatAgentName = default(string);

        /// <summary>
        /// Distance between the robot's wheels 
        /// </summary>
        [DataMember(Name = "WheelBase")]
        private double wheelBase = default(double);

        /// <summary>
        /// Maximum speed a wheel is permitted to turn
        /// </summary>
        [DataMember(Name = "MaxWheelSpeed")]
        private double maxWheelSpeed = default(double);

        /// <summary>
        /// The heartbeat agent
        /// </summary>
        private IAgentHost heartbeatAgent;

        /// <summary>
        /// Agent producing a mobile base velocity reference
        /// </summary>
        private IAgentHost mobileBaseVelocityReferenceProducerAgent;

        /// <summary>
        /// Forwarder for drive velocity commands
        /// </summary>
        private IForwarder<DifferentialDriveSetVelocityMessage> driveVelocityCommandForwarder;

        /// <summary>
        /// Initializes a new instance of the DifferentialDriveTrackingAgent class
        /// </summary>
        /// <param name="name">Agent name</param>
        /// <param name="mobileBaseVelocityReferenceProducer">The agent producing a mobile base velocity reference</param>
        /// <param name="heartbeatAgent">The heartbeat agent that accepts drive commands</param>
        /// <param name="wheelBase">Distance between the robot's wheels </param>
        /// <param name="maxWheelSpeed">Maximum speed a wheel is permitted to turn.</param>
        public DifferentialDriveTrackingAgent(
            string name, 
            IProducer<MobileBaseVelocityReferenceMessage> mobileBaseVelocityReferenceProducer,
            IControllable<DifferentialDriveSetVelocityMessage> heartbeatAgent, 
            double wheelBase, 
            double maxWheelSpeed)
            : base(name)
        {
            this.mobileBaseVelocityReferenceProducer = mobileBaseVelocityReferenceProducer.Name;
            this.heartbeatAgentName = heartbeatAgent.Name;
            this.wheelBase = wheelBase;
            this.maxWheelSpeed = maxWheelSpeed;
        }

        /// <summary>
        /// Called when agent is activated
        /// </summary>
        public override void OnActivated()
        {
            base.OnActivated();
            this.mobileBaseVelocityReferenceProducerAgent.Activate();
        }

        /// <summary>
        /// Called when agent is deactivated
        /// </summary>
        public override void OnDeactivated()
        {
            base.OnDeactivated();
            this.mobileBaseVelocityReferenceProducerAgent.Deactivate();
        }

        /// <summary>
        /// Called when agent is initialized
        /// </summary>
        /// <param name="locator">The agent locator</param>
        public override void Initialize(AgentLocator locator)
        {
            if (this.mobileBaseVelocityReferenceProducer == default(string))
            {
                throw new ArgumentException();
            }

            if (this.heartbeatAgentName == default(string))
            {
                throw new ArgumentException();
            }

            this.heartbeatAgent = locator.GetAgent(this.heartbeatAgentName);
            this.mobileBaseVelocityReferenceProducerAgent = locator.GetAgent(this.mobileBaseVelocityReferenceProducer);
            this.mobileBaseVelocityReferenceProducerAgent.Subscribe<MobileBaseVelocityReferenceMessage>(this);

            this.driveVelocityCommandForwarder =
                this.heartbeatAgent.GetControlPort<DifferentialDriveSetVelocityMessage>();

            base.Initialize(locator);
        }

        /// <summary>
        /// Called when a MobileBaseVelocityReferenceMessage is received
        /// </summary>
        /// <param name="message">A mobile base velocity reference message</param>
        public void Receive(MobileBaseVelocityReferenceMessage message)
        {
            double leftVel = (-message.MobileBaseVelocityReference.ThetaInRadiansPerSecond * this.wheelBase) / 2.0;
            double rightVel = (message.MobileBaseVelocityReference.ThetaInRadiansPerSecond * this.wheelBase) / 2.0;

            leftVel += message.MobileBaseVelocityReference.XInMetersPerSecond;
            rightVel += message.MobileBaseVelocityReference.XInMetersPerSecond;

            double maxCommandedSpeed = Math.Max(Math.Abs(leftVel), Math.Abs(rightVel));

            if (maxCommandedSpeed > this.maxWheelSpeed)
            {
                leftVel *= this.maxWheelSpeed / maxCommandedSpeed;
                rightVel *= this.maxWheelSpeed / maxCommandedSpeed;
            }

            DifferentialDriveVelocityCommand command = 
                new DifferentialDriveVelocityCommand((float)leftVel, (float)rightVel);

            this.driveVelocityCommandForwarder.Post(
                new DifferentialDriveSetVelocityMessage(command, message));
        }
    }
}
